import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: null,
    partnerInfo: null,
    token: null,
    isLogin: false,
    relationshipDays: 0,
    // 个人积分系统
    userPoints: 0,
    partnerPoints: 0
  }),
  
  getters: {
    userName: (state) => state.userInfo?.nickname || '我',
    partnerName: (state) => state.partnerInfo?.nickname || 'Ta',
    userAvatar: (state) => state.userInfo?.avatar || '/static/images/avatar1.png',
    partnerAvatar: (state) => state.partnerInfo?.avatar || '/static/images/avatar2.png',
    coupleNames: (state) => {
      const myName = state.userInfo?.nickname || '我'
      const partnerName = state.partnerInfo?.nickname || 'Ta'
      return `${myName} & ${partnerName}`
    }
  },
  
  actions: {
    setUserInfo(userInfo) {
      this.userInfo = userInfo
      this.isLogin = true
    },
    
    setPartnerInfo(partnerInfo) {
      this.partnerInfo = partnerInfo
    },
    
    setToken(token) {
      this.token = token
      uni.setStorageSync('token', token)
    },
    
    setUserPoints(points) {
      this.userPoints = points
    },
    
    setPartnerPoints(points) {
      this.partnerPoints = points
    },
    
    // 总积分计算
    get totalPoints() {
      return this.userPoints + this.partnerPoints
    },
    
    setRelationshipDays(days) {
      this.relationshipDays = days
    },
    
    logout() {
      this.userInfo = null
      this.partnerInfo = null
      this.token = null
      this.isLogin = false
      this.totalPoints = 0
      this.relationshipDays = 0
      uni.removeStorageSync('token')
    },
    
    async login(phone, password) {
      try {
        // 模拟登录API调用
        const mockUser = {
          id: 1,
          nickname: '小明',
          phone: '138****1234',
          avatar: '/static/images/avatar1.png'
        }
        const mockPartner = {
          id: 2,
          nickname: '小红',
          phone: '139****5678',
          avatar: '/static/images/avatar2.png'
        }
        
        this.setUserInfo(mockUser)
        this.setPartnerInfo(mockPartner)
        this.setToken('mock_token_123')
        this.setUserPoints(500)  // 每人500积分
        this.setPartnerPoints(500)
        this.setRelationshipDays(365)
        
        return { success: true }
      } catch (error) {
        return { success: false, message: error.message }
      }
    },
    
    async getUserProfile() {
      try {
        // 模拟获取用户信息API调用
        return {
          success: true,
          data: {
            user: this.userInfo,
            partner: this.partnerInfo,
            points: this.totalPoints,
            relationshipDays: this.relationshipDays
          }
        }
      } catch (error) {
        return { success: false, message: error.message }
      }
    }
  }
})